package com.coollang.smartbra.fragment;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.coollang.smartbra.R;
import com.coollang.smartbra.activity.RunningActivity;
import com.coollang.smartbra.base.BaseFragment;
import com.coollang.smartbra.base.MyApplication;
import com.coollang.smartbra.bleutil.BleUtil;
import com.coollang.smartbra.model.RunningDataModel;
import com.coollang.smartbra.presenter.RunningSettingFragmentPresenter;
import com.coollang.smartbra.utils.ActivitySwitcher;
import com.coollang.smartbra.utils.DisplayUtils;
import com.coollang.smartbra.utils.FormatUtils;
import com.coollang.smartbra.utils.GPSUtils;
import com.coollang.smartbra.utils.RunTimeUtils;
import com.coollang.smartbra.utils.TimeUtils;
import com.coollang.smartbra.utils.UIUtils;
import com.coollang.smartbra.views.CircularSeekBarBcg;

import java.text.DecimalFormat;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.realm.Realm;

/**
 * @Auther: Timmy
 * @Data: 2017/8/11
 * @Fuction:
 */

public class RunningSettingFragment extends BaseFragment {

    // =============================== View start =========================================
    @BindView(R.id.ll_start)
    LinearLayout mLlStart;
    @BindView(R.id.ll_run_small)
    LinearLayout mLlRunSmall;
    @BindView(R.id.ll_runing)
    LinearLayout mLlRuning;
    @BindView(R.id.btn_start)
    Button mBtnStart;
    @BindView(R.id.run_stop)
    TextView mRunStop;
    @BindView(R.id.circle_seekbar)
    CircularSeekBarBcg mCircleSeekbar;
    @BindView(R.id.rl_stop)
    RelativeLayout mRlStop;
    @BindView(R.id.tv_finish)
    TextView mTvFinish;
    @BindView(R.id.tv_continue)
    TextView mTvContinue;
    @BindView(R.id.run_time)
    TextView mRunTime;
    @BindView(R.id.running_time)
    TextView mRunningTime;
    @BindView(R.id.run_distance)
    TextView mTvRunDistance;
    @BindView(R.id.tv_distance)
    TextView mTvDistance;
    @BindView(R.id.run_heart_rate)
    TextView mTvHeart;
    @BindView(R.id.run_step)
    TextView mTvStep;
    @BindView(R.id.run_speed)
    TextView mTvSpeed;
    // =============================== View end =========================================

    Unbinder unbinder;
    private Timer mTimer;
    private TimerTask mTask;
    private RunningSettingFragmentPresenter mSettingFragmentPresenter;

    private long startTime;
    private long endTime;

    @Override
    protected View inflateView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.fragment_running_setting, null, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initView(View view) {
        mCircleSeekbar.setMaxProgress(1000);
        initLongClick();
    }

    @Override
    protected void initData() {
        mSettingFragmentPresenter = new RunningSettingFragmentPresenter(this);
        mSettingFragmentPresenter.initBlutTooth();
    }

    public void onScroll() {
        int visibility = mLlRunSmall.getVisibility();
        if (visibility == View.VISIBLE) {
            mLlRunSmall.setVisibility(View.GONE);
            mLlRuning.setVisibility(View.VISIBLE);
        } else if (visibility == View.GONE) {
            mLlRunSmall.setVisibility(View.VISIBLE);
            mLlRuning.setVisibility(View.GONE);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();


        RunTimeUtils.getInstance().stopTimer();
        BleUtil.getInstance().sendData((byte) 0x31, (byte) 0x04);

        mSettingFragmentPresenter.unBindBlueTooth();
    }

    // =============================================================================================

    @OnClick({R.id.btn_start, R.id.tv_continue, R.id.tv_finish})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_start:
                if (GPSUtils.isOPen(getActivity())) {
                    ActivitySwitcher.goCountTimeAct(getActivity(), mBtnStart);
                } else {
                    ((RunningActivity) getActivity()).showOpenGPSDialog();
                }
                break;
            case R.id.tv_continue:
                // 跳过
                continueRunning();
                break;
            case R.id.tv_finish:
                // 结束

                // 判断步数是否大于 100
                if (runStepNum > 10) {
                    toFinishRunning();
                } else {
                    ((RunningActivity) getActivity()).showFinishDialog();
                }
                break;
        }
    }

    // 开始运动
    public void startRunning() {
        mLlStart.setVisibility(View.GONE);
        mLlRunSmall.setVisibility(View.VISIBLE);
        startTime = System.currentTimeMillis();

        // 开始计时
        RunTimeUtils.getInstance().initTime();
        RunTimeUtils.getInstance().setTimeListener(mRunTimeListener);

        BleUtil.getInstance().sendData((byte) 0x31);
        ((RunningActivity) getActivity()).mActivityPresenter.startRunning();
    }

    /**
     * 运动开始计时
     */
    RunTimeUtils.RunTimeListener mRunTimeListener = new RunTimeUtils.RunTimeListener() {
        @Override
        public void onRunTimeChange(long timer) {

            mCurrentTime = timer;

            String formatTimeHHMMSS = TimeUtils.getFormatTimeHHMMSS(timer);

            if (mRunTime.getVisibility() == View.VISIBLE) {
                mRunTime.setText(formatTimeHHMMSS);
            }

            if (mRunningTime.getVisibility() == View.VISIBLE) {
                mRunningTime.setText(formatTimeHHMMSS);
            }

            // 计算配速
            // 距离 x 60 / 时间

            if (mCurrentTime != 0) {
                float rate = (mDistanceTotal / mCurrentTime) * 3600.0f;
                String[] split = (new DecimalFormat("#0.00").format(rate) + "").split("\\.");
                mTvSpeed.setText(split[0] + "'" + split[1] + "\"");
            }
        }
    };

    //****************************暂停 继续 按钮**********************************//
    private void initLongClick() {
        mRunStop.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        startCount();
                        break;
                    case MotionEvent.ACTION_UP:
                        if (mProgress >= 1000) {
                            setCircularSeekBarProgress(mProgress);
                            pauseRunning();
                        }
                        mTask.cancel();
                        mProgress = 0;
                        setCircularSeekBarProgress(0);
                        break;
                }
                return true;
            }
        });
    }

    private int mProgress;

    private void startCount() {
        if (mTimer == null) {
            mTimer = new Timer();
        }
        // 需要做的事:发送消息
        mTask = new TimerTask() {
            @Override
            public void run() {
                // 需要做的事:发送消息
                mProgress += 10;
                handler.sendEmptyMessage(1);
            }
        };
        mTimer.schedule(mTask, 0, 10);
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (mProgress > 1000) {
                        mTask.cancel();
                    } else {
                        setCircularSeekBarProgress(mProgress);
                    }
            }
        }
    };

    // 设置 progress 圆环
    private void setCircularSeekBarProgress(int progress) {
        mCircleSeekbar.setProgress(progress);
        mCircleSeekbar.invalidate();
    }

    // 暂停运动
    private void pauseRunning() {
        mRlStop.setVisibility(View.GONE);
        mTvFinish.setVisibility(View.VISIBLE);
        mTvContinue.setVisibility(View.VISIBLE);

        // 暂停计时
        RunTimeUtils.getInstance().setPause(true);

        // TODO: 暂停跑步
        BleUtil.getInstance().sendData((byte) 0x31, (byte) 0x02);

        open();
    }

    // 继续运动
    private void continueRunning() {
        continueRun();
        close();
    }

    private void continueRun() {
        // 开始计时
        RunTimeUtils.getInstance().setPause(false);
        // TODO: 继续运动指令
        BleUtil.getInstance().sendData((byte) 0x31, (byte) 0x03);
    }

    private void open() {
        ObjectAnimator.ofFloat(mTvContinue, "translationX", DisplayUtils.dip2px(getActivity(), 70)).setDuration(300).start();
        ObjectAnimator.ofFloat(mTvFinish, "translationX", -DisplayUtils.dip2px(getActivity(), 70)).setDuration(300).start();
    }

    private void close() {
        ObjectAnimator.ofFloat(mTvFinish, "translationX", 0).setDuration(300).start();
        ObjectAnimator.ofFloat(mTvContinue, "translationX", 0).setDuration(300).start();
        ObjectAnimator anim = ObjectAnimator.ofFloat(mTvContinue, "translationX", 0);
        anim.setDuration(300);
        // 回调监听，可以有也可以无。
        // 根据情况，如果需要监听动画执行到何种“进度”，那么就监听之。
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mProgress = 0;
                mRlStop.setVisibility(View.VISIBLE);
                mTvFinish.setVisibility(View.GONE);
                mTvContinue.setVisibility(View.GONE);
                setCircularSeekBarProgress(0);
            }
        });
        // 正式开始启动执行动画
        anim.start();
    }

    // 结束运动
    private void toFinishRunning() {
        // 运动结束
        // RunTimeUtils.getInstance().stopTimer();
        // BleUtil.getInstance().sendData((byte) 0x31, (byte) 0x04);
        ((RunningActivity) getActivity()).isRunningStart = false;
        ((RunningActivity) getActivity()).mActivityPresenter.stopRunning();
        endTime = System.currentTimeMillis();
        getActivity().finish();

        finishRunning();

        // 结束
        ((RunningActivity) getActivity()).gotoShareMapActivity();
    }


    public void showPromptDialog(byte zhengfan, byte qingxie) {
        if (alertDialog != null) {
            alertDialog.dismiss();
        }
        String message = "";

        if (zhengfan == 0 && qingxie == 0) {
            // 戴反也戴斜了
            message = "设佩戴反也戴斜了,请调整设备";
        } else if (zhengfan == 0 && qingxie == 1) {
            // 戴反了
            message = "设备戴反了,请调整设备";
        } else if (zhengfan == 1 && qingxie == 0) {
            // 戴斜了
            message = "设备戴斜了,请调整设备";
        } else if (zhengfan == 1 && qingxie == 1) {
            // 设备戴正确
            message = "设备佩戴正确,请开始运动吧";
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    alertDialog.dismiss();
                }
            }, 2000);
        }
        showDialog(message);

    }

    AlertDialog alertDialog;

    private void showDialog(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(message);
        alertDialog = builder.show();
    }

    // 移动的距离
    private float mDistanceTotal;
    private long mCurrentTime;

    /**
     * @param currLength 有问题
     */
    public void movingDistance(float currLength) {
        mDistanceTotal += currLength;
        // 计算公里数
        mTvDistance.setText(FormatUtils.decimalFormat(mDistanceTotal));
        mTvRunDistance.setText(FormatUtils.decimalFormat(mDistanceTotal));


    }

    // 设置步数和心率
    public void setStrpsAndHeart(long runSteps, int currentHeartRate) {
        runStepNum = runSteps;
        mTvStep.setText(runSteps + "");
        // mTvHeart.setText(currentHeartRate + "");

        setHeartRate(currentHeartRate);
    }

    // 设置心率假如过高.红色闪烁
    private void setHeartRate(int heartRate) {
        // 心率
        if (Integer.parseInt(MyApplication.mLogInDataBean.getIsalarm()) == 1) {
            if (heartRate >= Integer.parseInt(MyApplication.mLogInDataBean.getHr_alarm())) {
                mTvHeart.startAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.anim_alpha));
                mTvHeart.setTextColor(UIUtils.getColor(R.color.barrey_20));
            } else {
                mTvHeart.clearAnimation();
                mTvHeart.setTextColor(UIUtils.getColor(R.color.black));
            }
        }

        // 设置心率
        mTvHeart.setText(heartRate + "");
        mTvHeart.setTextSize(23);
    }

    private long runStepNum;

    // 结束运动,
    public void finishRunning() {
        // 存储数据
        RunningDataModel model = new RunningDataModel();

        model.setLength(mCurrentTime);
        model.setStarttime(startTime);
        model.setEndtime(endTime);
        model.setStep_nums(runStepNum);
        model.setMileage(mDistanceTotal);

        List<Integer> heartList = mSettingFragmentPresenter.mHeartList;
        heartList.add(100);

        // 心率最大值
        model.setMax_rate(Collections.max(heartList));
        // 心率最小值
        model.setMin_rate(Collections.min(heartList));
        // 求平均值
        model.setHeart_rate(getAve(heartList));

        Realm mRealm = Realm.getDefaultInstance();

        mRealm.beginTransaction();
        mRealm.copyToRealmOrUpdate(model);
        mRealm.commitTransaction();

    }

    // 求平均值
    private int getAve(List<Integer> list) {
        int sum = 0;
        int size = list.size();

        for (Integer number : list) {
            sum += number;

        }
        return sum / size;
    }
}
